//
//  ZMPictureView.swift
//  ZMWeiboSwift
//
//  Created by pg on 2017/7/31.
//  Copyright © 2017年 pg. All rights reserved.
//

import UIKit



class ZMPictureView: UICollectionView ,UICollectionViewDelegate,UICollectionViewDataSource{

    let flowLaout: UICollectionViewFlowLayout
    
    //数据源
    var images:[UIImage] = [UIImage]()
    
    //点击添加cell执行回调闭包
    var clickAddCellClosure: (()->())?
    
    //单元格之间的间距
    var itemMargin = 10
    //显示图片的   列数
    var cols = 3
    
    
    //添加图片的方法
    func addImage(image:UIImage){
        
        if images.count >= 9 {
            return
        }
        self.isHidden = false
        images.append(image)
        reloadData()
    }
     
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        flowLaout = UICollectionViewFlowLayout()
        
        super.init(frame: frame, collectionViewLayout: flowLaout)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    private func setupUI(){
        self.backgroundColor = UIColor.orange
        dataSource = self
        delegate = self
        
        //注册cell
        self.register(ZMPictureViewCell.self, forCellWithReuseIdentifier: "cell")
        
      
        
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        
        
        let itemWidth = (self.bounds.size.width - CGFloat((cols - 1)*itemMargin))/CGFloat(cols)
        
        flowLaout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flowLaout.minimumLineSpacing = CGFloat(itemMargin)
        flowLaout.minimumInteritemSpacing = CGFloat(itemMargin)
        
        
        
    }
    
    
}
extension ZMPictureView{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if images.count == 0 || images.count == 9 {
            return images.count
        }
        
        
        return images.count + 1
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ZMPictureViewCell
        
        if indexPath.item >= images.count {
            cell.image = nil
        }else
        {
            cell.image = images[indexPath.item]
            
        
        cell.currentIndexPath = indexPath
        
        cell.deleateButtonClickClosure = {[unowned self] (index) in
     
            self.images.remove(at: index)
            self.reloadData()
            if self.images.count == 0 {
                self.isHidden = true
            }
            
        }
        }
        return cell
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        clickAddCellClosure?()
        
    }
    
    
    
}


//MARK:-自定义单元格
class ZMPictureViewCell: UICollectionViewCell{
    
    //记录当前cell对应的indexpath
    var currentIndexPath: IndexPath?
    //点击删除按钮回调的闭包
    var deleateButtonClickClosure:((Int)->())?
    
    //懒加载imageview
    fileprivate lazy var imageView : UIImageView = {
        let imgview = UIImageView()
    
        return imgview
    }()
    
    //懒加载删除按钮
    fileprivate lazy var deleteButton: UIButton = {
        let btn = UIButton()
        
        btn.addTarget(self, action: #selector(deleteButtonClick), for: UIControlEvents.touchUpInside)
        btn.setImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
        btn.sizeToFit()
        return btn
    }()
    
    //数据源
    var image: UIImage?{
        didSet{
            if image != nil {
                imageView.image = image
                //有图片显示删除按钮
                deleteButton.isHidden = false
            }else{
                imageView.image = UIImage(named: "compose_pic_add")
                //没有图片,隐藏删除按钮
                deleteButton.isHidden = true
            }
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI(){
        self.backgroundColor = UIColor.red
        
        self.contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        //设置约束
        imageView.translatesAutoresizingMaskIntoConstraints = false
        
        contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .leading, relatedBy: .equal, toItem: contentView, attribute: .leading, multiplier: 1, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .bottom, relatedBy: .equal, toItem: contentView, attribute: .bottom, multiplier: 1, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .trailing , relatedBy: .equal, toItem: contentView, attribute: .trailing, multiplier: 1, constant: 0))
        //删除按钮约束
        deleteButton.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(5)
            make.trailing.equalToSuperview().offset(-5)
            
        }
        
    }
    
    //删除图片按钮
    func deleteButtonClick(){
        
        guard let item = currentIndexPath?.item else {
            return
        }
        deleateButtonClickClosure?(item)
    }
    
    
}



